package org.redis.cluster.transport.client.support;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.collections.CollectionUtils;
import org.apache.mina.util.ConcurrentHashSet;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.config.ClientConfig;
import org.redis.cluster.event.Event;
import org.redis.cluster.event.EventListener;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.scheduler.second.SecondScheduleEvent;
import org.redis.cluster.transport.client.Client;
import org.redis.cluster.transport.client.ClientPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientPoolMonitor implements ClientPool,Plugin,EventListener<SecondScheduleEvent> {
	
	private final static String CLIENT_POOL="defaultClientPool";
	
	private final static byte TEST_REQUEST[]="*1\r\n$4\r\nPING\r\n".getBytes();
	
	private final static byte TEST_RESPONSE[]="+PONG\r\n".getBytes();
	
	private final static String RETRY_COUNT_CONFIG="client_monitor_retry_count";
	
	private final static int DEFAULT_RETRY_COUNT=20;
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private RedisCluster redisCluster;
	private ClientPool clientPool;
	private int retryCount;
	
	private final static Collection<ClientConfig> configs=new ConcurrentHashSet<ClientConfig>();
	private final static Collection<ClientConfig> badConfigs=new ConcurrentHashSet<ClientConfig>();
	private final ConcurrentHashMap<ClientConfig, AtomicInteger> retryCounter=new ConcurrentHashMap<ClientConfig,AtomicInteger>();
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.clientPool=initClientPool();
		this.retryCount=initRetryCount();
	}
	
	@Override
	public void destroy() {
		
	}
	
	protected ClientPool initClientPool() {
		return redisCluster.getExtensionLoader().load(CLIENT_POOL,ClientPool.class);
	}
	
	protected int initRetryCount() {
		return redisCluster.getConfigManager().getSystemConfig().get(RETRY_COUNT_CONFIG).getValue(Integer.class, DEFAULT_RETRY_COUNT);
	}

	@Override
	public Client getClient(ClientConfig config) {
		if(badConfigs.contains(config)) {
			return null;
		}
		
		Client client=clientPool.getClient(config);
		if(client==null) {
			badConfigs.add(config);
		}
		else {
			configs.add(config);
		}
		
		return client;
	}

	@Override
	public boolean returnClient(ClientConfig config, Client client) {
		return clientPool.returnClient(config, client);
	}

	@Override
	public boolean destroy(ClientConfig config) {
		return clientPool.destroy(config);
	}
	
	@Override
	public void onEvent(SecondScheduleEvent event) {
		if(logger.isDebugEnabled()) {
			logger.debug("开始检测节点");
		}
		
		doClientTest();
		doBadClientTest();
		
		if(logger.isDebugEnabled()) {
			logger.debug("检测节点完成");
		}
	}
	
	@Override
	public boolean isSupport(Event event) {
		return (event instanceof SecondScheduleEvent);
	}
	
	protected void doClientTest() {
		if(CollectionUtils.isEmpty(configs)) {
			return;
		}
		
		for(ClientConfig config:configs) {
			if(doTest(config)) {
				retryCounter.remove(config);
				continue;
			}
			
			AtomicInteger counter=retryCounter.get(config);
			if(counter==null) {
				retryCounter.put(config, new AtomicInteger());
				counter=retryCounter.get(config);
			}
			
			if(counter.incrementAndGet()<retryCount) {
				continue;
			}
			
			retryCounter.remove(config);
			doRemoveConfig(config);
			
			if(logger.isInfoEnabled()) {
				logger.info("{} - 节点异常,已放入错误列表并销毁连接",config);
			}
		}
	}
	
	protected boolean doRemoveConfig(ClientConfig config) {
		badConfigs.add(config);
		configs.remove(config);
		clientPool.destroy(config);
		return true;
	}
	
	protected void doBadClientTest() {
		if(CollectionUtils.isEmpty(badConfigs)) {
			return;
		}
		
		for(ClientConfig badConfig:badConfigs) {
			if(!doTest(badConfig)) {
				continue;
			}
			
			doRemoveBadConfig(badConfig);
			
			if(logger.isInfoEnabled()) {
				logger.info("{} - 节点恢复",badConfig);
			}
		}
	}
	
	protected boolean doRemoveBadConfig(ClientConfig config) {
		badConfigs.remove(config);
		configs.add(config);
		return true;
	}
	
	protected boolean doTest(ClientConfig config) {
		try {
			Client client=clientPool.getClient(config);
			if(client==null) {
				return false;
			}
			
			byte response[]=client.send(TEST_REQUEST);
			boolean result=Arrays.equals(response, TEST_RESPONSE);
			
			if(!result) {
				clientPool.destroy(config);
			}
			else {
				clientPool.returnClient(config, client);
			}
			
			return result;
		}
		catch(Exception e) {
			if(logger.isDebugEnabled()) {
				logger.debug("",e);
			}
			
			return false;
		}
	}
	
	/**
	 * @return
	 */
	public static Collection<ClientConfig> getConfigs() {
		return new ArrayList<ClientConfig>(configs);
	}
	
	/**
	 * @return
	 */
	public static Collection<ClientConfig> getBadConfigs() {
		return new ArrayList<ClientConfig>(badConfigs);
	}
	
	public void setClientPool(ClientPool clientPool) {
		this.clientPool = clientPool;
	}
	public ClientPool getClientPool() {
		return clientPool;
	}
}